#!/usr/bin/env node
// Copyright 2017 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// =============================================================================

const fs = require('fs');
const path = require('path');
const shell = require('shelljs');

const IGNORE_DIRS = ['node_modules', 'dist', 'coverage'];

/** Returns all sub-dirs that contain package.json. */
function getPackageDirs(dir, filelist) {
  const files = fs.readdirSync(dir);
  filelist = filelist || [];
  files.forEach(file => {
    if (IGNORE_DIRS.indexOf(file) >= 0 || file.startsWith('.')) {
      return;
    }
    const childPath = path.join(dir, file);
    if (fs.statSync(childPath).isDirectory()) {
      filelist = getPackageDirs(childPath, filelist);
    } else if (file === 'package.json') {
      filelist.push(dir);
    }
  });
  return filelist;
};

function run(cmd, filePath) {
  if (shell.exec(cmd).code !== 0) {
    shell.echo('Failed running', cmd, 'on', filePath);
    shell.exit(1);
  }
}

function runYarn(filePath) {
  const cwd = process.cwd();
  shell.cd(filePath);
  shell.echo('=======================================================');
  shell.echo('Building', filePath);
  run('yarn prep', filePath);
  run('yarn build', filePath);
  run('yarn lint', filePath);
  shell.cd(cwd);
}

let dirs = getPackageDirs(process.cwd());
// Keep only packages that have the 'name' property.
dirs = dirs.filter(dir => require(path.join(dir, 'package.json')).name);
dirs.forEach(dir => runYarn(dir));
